"""
管理后台 - 用户管理接口
"""
from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import Optional, List
from pydantic import BaseModel

from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.core.permissions import require_permission, Permission
from app.models.user import User
from app.schemas.common import ApiResponse
from loguru import logger

router = APIRouter(prefix="/user", tags=["管理后台-用户"])


class UserListResponse(BaseModel):
    """用户列表响应"""
    list: List[dict]
    total: int
    page: int
    pageSize: int


@router.get("/list", response_model=ApiResponse[UserListResponse])
@require_permission(Permission.USER_VIEW)
async def get_user_list(
    page: int = Query(1, ge=1),
    pageSize: int = Query(20, ge=1, le=100),
    keyword: Optional[str] = Query(None),
    city: Optional[str] = Query(None),
    role: Optional[str] = Query(None),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取用户列表"""
    logger.info(f"📋 获取用户列表: page={page}")
    
    # 基础查询
    query = db.query(User)
    
    # 关键词搜索
    if keyword:
        query = query.filter(
            or_(
                User.nick_name.like(f"%{keyword}%"),
                User.phone.like(f"%{keyword}%")
            )
        )
    
    # 城市筛选
    if city:
        query = query.filter(
            or_(User.city_name == city, User.city_id == city)
        )
    
    # 角色筛选
    if role:
        query = query.filter(User.role == role)
    
    # 总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * pageSize
    users = query.order_by(User.created_at.desc()).offset(offset).limit(pageSize).all()
    
    # 转换为字典
    user_list = []
    for user in users:
        user_dict = user.to_dict()
        user_dict['role'] = getattr(user, 'role', 'user')
        user_list.append(user_dict)
    
    logger.success(f"✅ 返回用户列表: total={total}, count={len(user_list)}")
    
    return ApiResponse(data={
        "list": user_list,
        "total": total,
        "page": page,
        "pageSize": pageSize
    })


@router.get("/{user_id}", response_model=ApiResponse[dict])
@require_permission(Permission.USER_VIEW)
async def get_user_detail(
    user_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取用户详情"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(404, "用户不存在")
    
    user_dict = user.to_dict()
    user_dict['role'] = getattr(user, 'role', 'user')
    
    return ApiResponse(data=user_dict)


@router.post("/{user_id}/ban", response_model=ApiResponse[str])
@require_permission(Permission.USER_MANAGE)
async def ban_user(
    user_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """封禁用户"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(404, "用户不存在")
    
    # TODO: 添加 is_banned 字段
    # user.is_banned = True
    db.commit()
    
    return ApiResponse(message="用户已封禁")


@router.post("/{user_id}/unban", response_model=ApiResponse[str])
@require_permission(Permission.USER_MANAGE)
async def unban_user(
    user_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """解封用户"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(404, "用户不存在")
    
    # TODO: 添加 is_banned 字段
    # user.is_banned = False
    db.commit()
    
    return ApiResponse(message="用户已解封")

